mod database;
use anyhow::Ok;
use database::{save_role_perms, save_role_users, save_user_perms, save_user_roles};
use shq_common::prelude::Permission;
use crate::{authorization::database::{del_role_by_id, del_user_by_id}, cache::{RolePermission, UserPermission}};

pub async fn get_perms_by_role_id(role_id: u32)->anyhow::Result<Vec<(u32,Permission)>>{
    let mut rp = RolePermission::new()?;
    let perms = rp.get_perms_by_role_id(role_id).await?;
    Ok(perms)
}
pub async fn get_users_by_role_id(role_id: u32)->anyhow::Result<Vec<u32>>{
    let mut up = UserPermission::new()?;
    let perms = up.get_role_user_ids(role_id).await?;
    Ok(perms)
}
pub async fn get_perms_by_user_id(user_id: u32)->anyhow::Result<Vec<(u32,Permission)>>{
    let mut up = UserPermission::new()?;
    let perms = up.get_perms_by_user_id(user_id).await?;
    Ok(perms)
}
pub async fn get_roles_by_user_id(user_id: u32)->anyhow::Result<Vec<u32>>{
    let mut up = UserPermission::new()?;
    let perms = up.get_user_role_ids(user_id).await?;
    Ok(perms)
}

pub async fn perms_to_user(user_id: u32, perms: Vec<(u32,Permission)>) -> anyhow::Result<()> {
    save_user_perms(user_id, perms).await?;
    let mut up = UserPermission::new()?;
    up.del_user_permission(user_id)?;
    Ok(())
}
pub async fn perms_to_role(role_id: u32, perms: Vec<(u32,Permission)>) -> anyhow::Result<()> {
    save_role_perms(role_id, perms).await?;
    let mut rp = RolePermission::new()?;
    rp.del_role(role_id)?;
    Ok(())
}
pub async fn users_to_role(role_id: u32, user_ids: Vec<u32>) -> anyhow::Result<()> {
    save_role_users(role_id, user_ids.as_slice()).await?;
    let mut up = UserPermission::new()?;
    up.del_role_user_with_ids(role_id,user_ids.as_slice())?;
    up.del_role_user(role_id)?;
    Ok(())
}
pub async fn roles_to_user(user_id: u32, role_ids: Vec<u32>) -> anyhow::Result<()> {
    save_user_roles(user_id, role_ids.as_slice()).await?;
    let mut up = UserPermission::new()?;
    up.del_user_role_with_ids(user_id,role_ids.as_slice())?;
    up.del_user_role(user_id)?;
    Ok(())
}
pub async fn del_role(role_id: u32) -> anyhow::Result<()> {
    del_role_by_id(role_id).await?;
    let mut rp = RolePermission::new()?;
    rp.del_role(role_id)?;
    let mut up = UserPermission::new()?;
    let uids=up.get_role_user_ids(role_id).await?;
    up.del_role_user(role_id)?;
    for user_id in uids {
        up.del_user_role_with_ids(user_id,&[role_id])?;
    }
    Ok(())
}
pub async fn del_user(user_id: u32) -> anyhow::Result<()> {
    del_user_by_id(user_id).await?;
    let mut up =UserPermission::new()?;
    up.del_user_permission(user_id)?;
    let rids=up.get_user_role_ids(user_id).await?;
    up.del_user_role(user_id)?;
    for role_id in rids {
        up.del_user_role_with_ids(role_id,&[user_id])?;
    }
    Ok(())
}
